import { Directive } from "vue";

// 记录每个元素需要执行的回调
const map = new WeakMap();

const observer = new ResizeObserver((entries) => {
    for (const entry of entries) {
        const callback = map.get(entry);
        if (typeof callback === 'function') callback({
            width: entry.contentBoxSize[0].inlineSize,
            height: entry.contentBoxSize[0].blockSize,
        })
    }
});

export default <Directive>{
    mounted(el, binding) {
        observer.observe(el);
        map.set(el, binding);
    },
    unmounted(el) {
        observer.unobserve(el);
    },
};